import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:loan_market/confit/network.dart';
import 'package:loan_market/confit/screen_adapter.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _list = new List(); //列表要展示的数据
  int currentPage = 0; //第一页
  int totalSize = 0; //总条数

  String _localPath = '';
  String downloadId;
  ReceivePort _port = ReceivePort();

  bool isApk = false;
  String fileName = '';

  String _clientId = ''; //应用唯一id
  String _phoneType = ''; //机型
  String _osVersion = ''; //系统版本号

  String loadMoreText = "";
  TextStyle loadMoreTextStyle =
      new TextStyle(color: const Color(0xFF999999), fontSize: 14.0);
  TextStyle titleStyle =
      new TextStyle(color: const Color(0xFF757575), fontSize: 14.0);

  //初始化滚动监听器，加载更多使用
  ScrollController _controller = new ScrollController();

  _HomePageState() {
    //固定写法，初始化滚动监听器，加载更多使用
    _controller.addListener(() {
      var maxScroll = _controller.position.maxScrollExtent;
      var pixel = _controller.position.pixels;
      if (maxScroll == pixel && _list.length < totalSize) {
        setState(() {
          loadMoreText = "Loading...";
          loadMoreTextStyle =
              new TextStyle(color: const Color(0xFF4483f6), fontSize: 14.0);
        });
        loadMoreData();
      } else {
        setState(() {
          loadMoreText = "- - - - The end - - - -";
          loadMoreTextStyle =
              new TextStyle(color: const Color(0xFF999999), fontSize: 10.0);
        });
      }
    });
  }

  //加载列表数据
  loadMoreData() async {
    this.currentPage++;
    var res = await NetWork().get('appBiz/confList/$currentPage/20');
    int code = res['status'];
    if (code == 200) {
      setState(() {
        _list.addAll(res['data']['bizResponses']);
        totalSize = res['data']['page']['totalElements'];
      });
    } else {
      Fluttertoast.showToast(
        msg: 'Server failed',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }
  }

  //进入应用上传此接口 统计用户活跃度
  appVestActivation() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    print('${androidInfo.androidId}');
    print('${androidInfo.device}');
    print('${androidInfo.version.release}');
    setState(() {
      _clientId = '${androidInfo.androidId}';
      _phoneType = '${androidInfo.device}';
      _osVersion = '${androidInfo.version.release}';
    });
    var res = await NetWork().post('report/appVestActivation', data: {
      'appKey': NetWork.appKey,
      'clientId': _clientId,
      'phoneType': _phoneType,
      'osVersion': _osVersion,
    });
    int code = res['status'];
    if (code == 200) {
      print('okokokokokokoko');
    } else {
      print('errrrrror');
    }
  }

  //点击To Apply按钮传此接口，统计点击活跃度
  appBizApply(int id, int gotype) async {
    print('id === >>>>   $id');
    var res = await NetWork().post('report/appBizApply', data: {
      'appBizId': id,
      'appKey': NetWork.appKey,
      'clientId': _clientId,
      'phoneType': _phoneType,
      'osVersion': _osVersion,
      'goType': gotype,
    });
    int code = res['status'];
    if (code == 200) {
      print('appBizApply  ===  okokokokok');
    } else {
      print('appBizApply  ===  errrrrrrror');
    }
  }

  ///初始化
  Future<void> _init() async {
    await FlutterDownloader.initialize();
    IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');

    _port.listen((dynamic data) {
      print('UI Isolate Callback: $data');
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];

      print("状态111: $status");
      print("进度111: $progress");
      print("id == downloadId: ${id == downloadId}");
      if (progress == 100) {
        print('okkookokokok........   $_localPath');
        Fluttertoast.showToast(
          msg: 'Download complete',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
        OpenFile.open("$_localPath/$fileName");
      }
    });
    //下载回调
    FlutterDownloader.registerCallback(downloadCallback);
    //保存目录
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    //判断目录是否存在  不存在则创建
    if (!hasExisted) {
      savedDir.create();
    }
  }

  ///回调
  static void downloadCallback(
      String id, DownloadTaskStatus status, int progress) {
    // print('背景分离回调: 任务id ($id)  \n状态 ($status)  \n进度 ($progress)');
    final SendPort send =
        IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send([id, status, progress]);
  }

  //下载apk
  downloadApk(String url) async {
    // await FlutterDownloader.initialize();
    final directory = await getExternalStorageDirectory();
    setState(() {
      _localPath = directory.path;
    });

    final taskId = await FlutterDownloader.enqueue(
      url: '$url',
      savedDir: _localPath,
      showNotification: true,
      openFileFromNotification: true,
    );
    downloadId = taskId;
  }

  // 检查权限
  Future<bool> _checkPermission() async {
    if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  //打开google应用市场
  launchUrl(String id) async {
    String url = 'https://play.google.com/store/apps/details?id=$id';
    print('url === >>>>  $url');
    if (await canLaunch(url)) {
      await (launch(url));
    } else {
      Fluttertoast.showToast(
        msg: 'Open fail',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }
  }

  @override
  void initState() {
    super.initState();
    _init();
    loadMoreData();
    appVestActivation();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  Widget _nullView() {
    return Center(
        child: Column(children: <Widget>[
      SizedBox(
        height: ScreenAdapter.height(200),
      ),
      Image.asset(
        'images/loading.png',
        width: ScreenAdapter.width(556),
        height: ScreenAdapter.height(556),
      ),
    ]));
  }

  //下拉刷新,必须异步async不然会报错
  Future _pullToRefresh() async {
    currentPage = 0;
    _list.clear();
    loadMoreData();
    return null;
  }

  Widget _buildProgressMoreIndicator() {
    return new Padding(
      padding: const EdgeInsets.all(15.0),
      child: new Center(
        child: loadMoreText.toString() == ''
            ? Container()
            : new Text(loadMoreText, style: loadMoreTextStyle),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index == _list.length) {
      return _buildProgressMoreIndicator();
    } else {
      return itemView(index);
    }
  }

  Widget itemView(int i) {
    return Container(
        padding: EdgeInsets.fromLTRB(
            ScreenAdapter.width(34),
            ScreenAdapter.width(20),
            ScreenAdapter.width(50),
            ScreenAdapter.width(0)),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(right: ScreenAdapter.width(20)),
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(5),
                      child: _list[i]['icon'] == ''
                          ? Image.asset(
                              'images/img.png',
                              height: ScreenAdapter.height(130),
                              width: ScreenAdapter.width(130),
                              fit: BoxFit.cover,
                            )
                          : Image.network(
                              '${_list[i]['icon']}',
                              height: ScreenAdapter.width(100),
                              width: ScreenAdapter.width(100),
                              fit: BoxFit.cover,
                            )),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          itemName(i),
                          itemBtn(i),
                        ],
                      ),
                      Text('${_list[i]['intro']}', maxLines: 1, overflow: TextOverflow.ellipsis,),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: ScreenAdapter.height(20),),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                itemAmount(i),
                itemInfo(i),
              ],
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  0, ScreenAdapter.height(20), 0, ScreenAdapter.height(0)),
              child: Divider(
                height: 2,
              ),
            ),
          ],
        ));
  }

  Widget itemName(int i) {
    return Row(
      children: <Widget>[
        Text('${_list[i]['name']}',
            style: TextStyle(
                fontSize: ScreenAdapter.size(31),
                color: Color(0xFF373238),
                fontWeight: FontWeight.bold)),
        SizedBox(
          width: ScreenAdapter.width(9),
        ),
        //此处需要添加hot按钮
        Container(
          alignment: Alignment.center,
          height: ScreenAdapter.height(22),
          padding: EdgeInsets.fromLTRB(
              ScreenAdapter.width(7), 0, ScreenAdapter.width(7), 0),
          decoration: BoxDecoration(
              color: Color('${_list[i]['tagColor']}' == ''
                  ? 0xFFFFFFFF
                  : int.parse('0xFF${_list[i]['tagColor']}')),
              borderRadius: BorderRadius.circular(2.5)),
          child: '${_list[i]['tag']}' == ''
              ? Container()
              : Text(
                  '${_list[i]['tag']}',
                  style: TextStyle(
                      fontSize: ScreenAdapter.size(14),
                      color: Color(0xFFFFFFFF)),
                ),
        ),
      ],
    );
  }

  //按钮
  Widget itemBtn(int i) {
    return InkWell(
        onTap: () async {
          print(
              'pkgName === >>  ${_list[i]['pkgName']}   goType ==  ${_list[i]['gotype']}  goUrl  == >>  ${_list[i]['gourl']}');
          appBizApply(_list[i]['id'], _list[i]['gotype']); //统计

          if (_list[i]['gotype'] == 1) {
            //跳转到应用市场
            launchUrl('${_list[i]['pkgName']}');
          } else {
            //下载apk
            String gourl = '${_list[i]['gourl']}';
            String subUrl = gourl.substring(gourl.length - 3, gourl.length);
            print('goUrl === >>>  $gourl   subUrl == >>>  $subUrl');
            print('gourl === >>>  ${gourl.endsWith('.apk')}');
            print('lastIndexOf === >>>  ${gourl.lastIndexOf('/')}');
            print(
                'subString == >>>>  ${gourl.substring(gourl.lastIndexOf('/') + 1, gourl.length)}');
            setState(() {
              isApk = gourl.endsWith('.apk');
              fileName =
                  gourl.substring(gourl.lastIndexOf('/') + 1, gourl.length);
            });
            if (await _checkPermission()) {
              // await downloadApk(gourl);
              //是不是已apk结尾
              if (isApk) {
                await downloadApk(gourl);
              } else {
                Fluttertoast.showToast(
                  msg: 'Apk format error',
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.CENTER,
                );
                return;
              }
            }
          }
        },
        child: Container(
          alignment: Alignment.center,
          height: ScreenAdapter.height(50),
          padding: EdgeInsets.fromLTRB(
              ScreenAdapter.width(30), 0, ScreenAdapter.width(30), 0),
          margin: EdgeInsets.all(ScreenAdapter.width(10)),
          decoration: BoxDecoration(
            border: new Border.all(color: Color(0xFF2F7BD9), width: 1), // 边色与边宽度
              borderRadius: BorderRadius.circular(25)),
          child: Text(
            'To Detail',
            style: TextStyle(
                fontSize: ScreenAdapter.size(27), color: Color(0xFF2F7BD9)),
          ),
        ));
  }

  Widget itemAmount(int i) {
    return Container(
      padding: EdgeInsets.only(left: ScreenAdapter.width(12)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Text(
            '${_list[i]['amount']}',
            style: TextStyle(
                fontSize: ScreenAdapter.size(36),
                color: Color(0xFF373238)),
          ),
          SizedBox(
            height: ScreenAdapter.height(10),
          ),
          Text(
            'Max Amount(Rp)',
            style: TextStyle(
                fontSize: ScreenAdapter.size(22), color: Color(0xFF918F94)),
          ),
        ],
      ),
    );
  }

  Widget itemInfo(int i) {
    return Container(
      padding: EdgeInsets.only(right: ScreenAdapter.width(60)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Text(
            'Interest : ${_list[i]['interest']}% / ${_list[i]['interestSuffix']}',
            style: TextStyle(
                fontSize: ScreenAdapter.size(22), color: Color(0xFF918F94)),
          ),
          SizedBox(
            height: ScreenAdapter.height(16),
          ),
          Text(
            'Tenure : ${_list[i]['tenure']} ${_list[i]['tenureSuffix']}',
            style: TextStyle(
                fontSize: ScreenAdapter.size(22), color: Color(0xFF918F94)),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          elevation: 0.0,
          backgroundColor: Color(0xFF2F7BD9),
          brightness: Brightness.light,
          title: Text(
            'Pinjaman kariaku',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Color(0xFF333333),
              fontWeight: FontWeight.w500,
              fontSize: ScreenAdapter.size(40),
            ),
          ),
        ),
        body: SafeArea(
            child: _list.length == 0
                ? _nullView()
                : new RefreshIndicator(
                    onRefresh: _pullToRefresh,
                    child: ListView.builder(
                      controller: _controller, //指明控制器加载更多使用
                      itemCount: _list.length + 1,
                      itemBuilder: _renderRow,
                    ))));
  }
}
